import decimal
from datetime import timedelta, datetime

from flask import jsonify, request, Blueprint
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import func

from app import db
from app.models import User
from app.models.commission import CommissionLog, WithdrawLog

# 创建蓝图
commission_bp = Blueprint('mp_commission', __name__)


@commission_bp.route("/list", methods=["GET"])
def commission_list():
    user_id = request.args.get("user_id", type=int)
    page = request.args.get("page", default=1, type=int)
    page_size = request.args.get("page_size", default=10, type=int)

    if not user_id:
        return jsonify({"error": "缺少 user_id"}), 400

    query = CommissionLog.query.filter_by(to_user_id=user_id).order_by(CommissionLog.created_at.desc())

    total = query.count()
    records = query.offset((page - 1) * page_size).limit(page_size).all()

    from_user_ids = [r.from_user_id for r in records]
    users = User.query.filter(User.user_id.in_(from_user_ids)).all()  # 注意这里改成 user_id
    user_map = {u.user_id: u.nick_name for u in users}  # 这里也改

    data = []
    for r in records:
        data.append({
            "order_id": r.order_id,
            "from_user_id": r.from_user_id,
            "from_user_name": user_map.get(r.from_user_id, ""),
            "amount": float(r.amount),
            "rate": float(r.rate),
            "created_at": r.created_at.strftime("%Y-%m-%d %H:%M:%S")
        })

    # 全部佣金总额（to_user_id 对应用户）
    total_amount_all = db.session.query(db.func.sum(CommissionLog.amount)) \
                           .filter(CommissionLog.to_user_id == user_id).scalar() or 0

    return jsonify({
        "total": total,
        "total_amount": float(total_amount_all),  # 全部历史总收益
        "list": data
    })


@commission_bp.route("/details", methods=["GET"])
def get_commission_summary():
    user_id = request.args.get("user_id", type=int)
    if not user_id:
        return jsonify({"error": "缺少 user_id"}), 400

    now = datetime.now()

    # 今日
    start_today = now.replace(hour=0, minute=0, second=0, microsecond=0)
    end_today = now

    # 昨日
    start_yesterday = start_today - timedelta(days=1)
    end_yesterday = start_today

    # 本月
    start_this_month = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)

    # 上月
    first_day_last_month = (start_this_month - timedelta(days=1)).replace(day=1)
    last_day_last_month = start_this_month - timedelta(seconds=1)

    def sum_commission(start_time, end_time):
        from sqlalchemy import func
        return CommissionLog.query.with_entities(func.coalesce(func.sum(CommissionLog.amount), 0)) \
            .filter(
            CommissionLog.to_user_id == user_id,
            CommissionLog.created_at >= start_time,
            CommissionLog.created_at < end_time
        ).scalar()

    result = {
        "today": float(sum_commission(start_today, end_today)),
        "yesterday": float(sum_commission(start_yesterday, end_yesterday)),
        "this_month": float(sum_commission(start_this_month, end_today)),
        "last_month": float(sum_commission(first_day_last_month, last_day_last_month))
    }

    return jsonify({
        "code": 1,
        "data": result
    })


@commission_bp.route("/balance", methods=["GET"])
@jwt_required()
def get_balance():
    user_id = get_jwt_identity()  # 取出登录信息，类型是dict
    if not user_id:
        return jsonify({"code": 0, "msg": "未获取到用户ID"}), 400

    user = User.query.get(user_id)
    if not user:
        return jsonify({"code": 0, "msg": "用户不存在"}), 404

    return jsonify({
        "code": 1,
        "balance": str(user.balance)  # 转成字符串避免序列化错误
    })


@commission_bp.route("/apply_withdraw", methods=["POST"])
@jwt_required()
def apply_withdraw():
    user_id = get_jwt_identity()  # 取出登录信息，类型是dict
    if not user_id:
        return jsonify({"code": 0, "msg": "未获取到用户ID"}), 400

    user = User.query.get(user_id)
    if not user:
        return jsonify({"code": 0, "msg": "用户不存在"}), 404

    data = request.json
    amount = data.get('amount')
    account = data.get('account')
    realname = data.get('realname')  # 如果需要实名

    if not amount or not account or not realname:
        return jsonify({"msg": "缺少必要参数"}), 400

    try:
        amount = decimal.Decimal(str(amount))
        if amount <= 0:
            return jsonify({"msg": "提现金额必须大于0"}), 400
    except:
        return jsonify({"msg": "提现金额格式错误"}), 400

    # 查询用户余额（假设User有balance字段）
    user = User.query.get(user_id)
    if not user:
        return jsonify({"msg": "用户不存在"}), 404

    if user.balance < amount:
        return jsonify({"msg": "余额不足"}), 400

    # 创建提现记录
    withdraw_log = WithdrawLog(
        user_id=user_id,
        amount=amount,
        status='pending',
        method='alipay',  # 这里写死支付宝提现
        account=account,
        remark=f'实名：{realname}'
    )
    db.session.add(withdraw_log)

    # 扣除余额（假设直接扣除）
    user.balance -= amount

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify({"msg": "服务器错误，提交失败"}), 500

    return jsonify({"msg": "提现申请提交成功"}), 200


@commission_bp.route('/list_withdraw', methods=['GET'])
@jwt_required()
def list_withdraws():
    user_id = get_jwt_identity()
    page = request.args.get('page', default=1, type=int)
    per_page = request.args.get('per_page', default=10, type=int)

    query = WithdrawLog.query.filter_by(user_id=user_id)

    pagination = query.order_by(WithdrawLog.created_at.desc()).paginate(page=page, per_page=per_page, error_out=False)

    items = [item.to_dict() for item in pagination.items]

    return jsonify({
        "code": 1,
        "msg": "获取成功",
        "data": {
            "items": items,
            "total": pagination.total,
            "page": pagination.page,
            "pages": pagination.pages
        }
    })


# 注册蓝图
def init_app(app):
    app.register_blueprint(commission_bp, url_prefix='/api/admin/mp/commission')
